package com.example.springcloud;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * 主启动类
 */
@Slf4j
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix

public class PaymentMainAppHystrixOn8001 {

    /**
     * 主方法
     *
     * @param args the input arguments
     */
    public static void main(String[] args) {

        ConfigurableApplicationContext app = SpringApplication.run(PaymentMainAppHystrixOn8001.class, args);

        // 得到所有的bean
        String[] beanNames = app.getBeanDefinitionNames();

        StringBuilder beanList = new StringBuilder();

        // 打印容器中所有的组件
        for (int i = 0; i < beanNames.length; i++) {
            beanList.append("\n").append(i + 1).append(" ").append(beanNames[i]);
        }

        log.info(String.valueOf(beanList));
    }

    /**
     * 此配置是为了服务监控而配置，
     * 与服务容错本身无关，
     * springCloud 升级之后的坑
     * ServletRegistrationBean
     * 因为 springboot 的默认路径不是/hystrix.stream *
     * 只要在自己的项目中配置上下面的 servlet 即可
     */
    @Bean
    public ServletRegistrationBean getServlet() {

        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean<HystrixMetricsStreamServlet>
                registrationBean = new ServletRegistrationBean<>(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream"); // 记得加工程名，这是自己给自己挖的坑
        registrationBean.setName("HystrixMetrics StreamServlet");
        return registrationBean;
    }

}
